package com.study.rcp.framework.view;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.wb.swt.SWTResourceManager;

import com.bsf.generator.CodeAutoGenerator;
import com.bsf.generator.entity.AutoGenInf;
import com.bsf.generator.entity.TableInfEntity;
import com.bsf.generator.util.MyExcelHelper;
import com.study.rcp.framework.core.Console;


public class AutoGeneratorCodeView extends ViewPart {
	public AutoGeneratorCodeView() {
	}

	private Text text;
	private Table table;
	CheckboxTableViewer checkTableView;
	Composite composite;
	public static final String ID = "rcpframework.view";
	List<Map<String, Object>>  excelTables = new ArrayList<Map<String,Object>>();
	public void createPartControl(Composite parent) {
		// setup bold font
		Font boldFont = JFaceResources.getFontRegistry().getBold(
				JFaceResources.DEFAULT_FONT);
		composite = new Composite(parent, SWT.NONE);

		Group group = new Group(composite, SWT.NONE);
		group.setText("参数列表");
		group.setBounds(10, 10, 1256, 75);
		group.setFont(boldFont);
		text = new Text(group, SWT.BORDER);
		text.setEditable(false);
		text.setBounds(10, 24, 401, 27);

		Button button = new Button(group, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FileDialog dialog = new FileDialog(composite.getShell(),
						SWT.OPEN);
				dialog.setFilterPath("");// 设置默认的路径
				dialog.setText("选择文件");// 设置对话框的标题
				dialog.setFileName("");// 设置默认的文件名
				dialog.setFilterNames(new String[] { "Excel文件 (*.xls)"});// 设置扩展名"所有文件(*.*)" });// 设置扩展名
				dialog.setFilterExtensions(new String[] { "*.xls"});//, "*.*" });// 设置文件扩展名
				String fileName = dialog.open();//
				if(fileName==null || "".equals(fileName)){
					return;
				}
				text.setText(fileName);
				Console.info(String.format("选择的数据文件:[%s]",fileName));
				checkTableView.setInput(getInitParams());
				checkTableView.setAllChecked(true);
			}
		});
		button.setBounds(417, 22, 80, 29);
		button.setText("\u9009\u62E9\u6570\u636E\u6587\u4EF6");
		button.setFont(boldFont);

		Group group_2 = new Group(composite, SWT.NONE);
		group_2.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9,
				SWT.BOLD));
		group_2.setText("数据信息");
		group_2.setBounds(10, 102, 1256, 443);
		createTable(group_2);
		checkTableView = new CheckboxTableViewer(table);
		checkTableView.setLabelProvider(new PersonLabelProvider());
		checkTableView.setContentProvider(new PersonContentProvider());
		createToolBar(group_2);
		
	}
	/**
	 * 创建表
	 * @param parent
	 */
	private void createTable(Composite parent) {
		//先创建表 注意style中要包含 SWT.CHECK
		table = new Table(parent, SWT.CHECK|SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL);
		table.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
		table.setBounds(10, 52, 1236, 380);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		//设置表头
		String[] tableCols = {"编号" , "代码包名" ,"实体名", "表名" , "中文表名", "作者","数据库类型","说明"};
		int i=0;
		for(String colStr : tableCols) {
			TableColumn tc = new TableColumn(table, SWT.LEFT); //靠左
			tc.setText(colStr);
			if(i==0){
				tc.setWidth(50);
			}else{
				tc.setWidth(150);
			}
			i++;
			
		}
		//设置line 和header显示
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		
		//创建tableview
		checkTableView = new CheckboxTableViewer(table);
		checkTableView.setLabelProvider(new PersonLabelProvider());
		checkTableView.setContentProvider(new PersonContentProvider());
		
	}
	public void setFocus() {
	}
	
	
	/**
	 * 创建工具栏
	 * @param parent
	 */
	private void createToolBar(Composite parent) {
		//添加工具栏
		ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.WRAP | SWT.RIGHT);
		toolBar.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 9, SWT.BOLD));
		toolBar.setBounds(10, 21, 150, 25);
		//添加工具项
		ToolItem allCheck = new ToolItem(toolBar, SWT.NONE);
		allCheck.setText("全选");
		
		new ToolItem(toolBar, SWT.SEPARATOR);
		
		//添加工具项
		ToolItem rickCheck = new ToolItem(toolBar, SWT.NONE);
		rickCheck.setText("反选");
		
		new ToolItem(toolBar, SWT.SEPARATOR);
		
		//添加工具项
		ToolItem showCheck = new ToolItem(toolBar, SWT.NONE);
		showCheck.setText("生成代码");
		
		//添加监听
		allCheck.addListener(SWT.Selection, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				Display.getDefault().asyncExec(new Runnable() {
					
					@Override
					public void run() {
						//全选
						checkTableView.setAllChecked(true);
						
					}
				});
				
				
			}
		});
		
		rickCheck.addListener(SWT.Selection, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				
				Display.getDefault().asyncExec(new Runnable() {
					
					@SuppressWarnings("unchecked")
					@Override
					public void run() {
						List<Map<String, Object>> list =  (List<Map<String, Object>>) checkTableView.getInput();
						
						//进行反选
						for(Map<String, Object> p : list) {
							checkTableView.setChecked(p, !checkTableView.getChecked(p));
						}
						
					}
				});
			
			}
		});
		
		//查看选则
		showCheck.addListener(SWT.Selection, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				final Object[] checks = checkTableView.getCheckedElements();
				
				//如果选则为空 提示下
				if(checks == null || checks.length == 0) {
					MessageDialog.openInformation(Display.getDefault().getActiveShell(), "提示", "请选择需要生成代码的数据!");
					return;
				}
				DirectoryDialog dirDlg = new DirectoryDialog(composite.getShell()); 
			    dirDlg.setText("选择文件夹"); 
			    dirDlg.setMessage("选择保存代码的文件夹"); 
			    dirDlg.setFilterPath("c:/Downloads"); 
			    final String dir = dirDlg.open();
			    if(dir==null || "".equals(dir)){
					return;
				}
			    Console.info(String.format("选择的保存文件路径:[%s]",dir));
				 ProgressMonitorDialog progress = new ProgressMonitorDialog(null);
	                try {
	                    progress.run(true, true, new IRunnableWithProgress() {
	                        @SuppressWarnings("unchecked")
							public void run(IProgressMonitor monitor) throws InvocationTargetException,    InterruptedException {
	                            monitor.beginTask("生成代码", IProgressMonitor.UNKNOWN);
	                            monitor.setTaskName("生成代码");
	                            if(monitor.isCanceled()){
	                            	return;
	                            }
	            				//转换为字符串弹出dialog
	            				for(Object obj : checks) {
	            					Map<String, Object> map=(Map<String, Object>)obj;
	            					TableInfEntity tbinf = (TableInfEntity) map.get(TableInfEntity.TABLEINFENTITY);
	            					Console.info("生成["+tbinf.getTableName()+"]-"+tbinf.getTableDescription()+"开始...");
	            					CodeAutoGenerator.generator(map, true,dir);
	            					Console.info("生成成功[OK]");
	            				}
	            				 monitor.done();
	                        } 
	                    });
	                } catch (InvocationTargetException e) {
	                    e.printStackTrace();
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
			}
		});
		
	}
	
	/**
	 * 初始化一些参数进来
	 * @return
	 */
	private List<Map<String, Object>> getInitParams() {
		excelTables.clear();//清空所有
			try {
				List<Map<String, Object>> ts = MyExcelHelper.getAllTables(new File(text.getText()), true);
				excelTables.addAll(ts);
			} catch (Exception err) {
				err.printStackTrace();
			}
		return excelTables;
		
	}

	/**
	 * 标签管理
	 * @author lyf
	 *
	 */
	private class PersonLabelProvider extends LabelProvider implements
			ITableLabelProvider {

		@Override
		public Image getColumnImage(Object element, int columnIndex) {
			// TODO Auto-generated method stub
			return null;
		}

		@SuppressWarnings("unchecked")
		@Override
		public String getColumnText(Object element, int columnIndex) {
			Map<String, Object> map=((Map<String, Object>) element);
			AutoGenInf af = (AutoGenInf) map.get(AutoGenInf.AUTOGENINF);
			TableInfEntity tbinf = (TableInfEntity) map.get(TableInfEntity.TABLEINFENTITY);
			switch (columnIndex) {
			case 0:
				return tbinf.getId();
			case 1:
				return af.getAuthGenPath();
			case 2:
				return af.getEntityId();
			case 3:
				return tbinf.getTableName();
			case 4:
				return tbinf.getTableDescription();
			case 5:
				return af.getAuthor();
			case 6:
				return af.getDbType();
			case 7:
				return "";
			default:
				return "";
			}
			
		}

	}
	
	/**
	 * 内容管理
	 * 
	 * @author lyf
	 * 
	 */
	private class PersonContentProvider implements
			IStructuredContentProvider {

		@Override
		public void dispose() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			// TODO Auto-generated method stub
			
		}

		@SuppressWarnings("rawtypes")
		@Override
		public Object[] getElements(Object inputElement) {
			if(inputElement instanceof List) {
				return ((List)inputElement).toArray();
			}
			return new Object[0];
		}
		
	}
}
